package tjs.study.notes.dotest.jdk.thread;

/**
 * Created by Nicky.Tang on 2021/11/19 7:44 上午
 * 测试线程间的通讯
 *
 * @since 02.12.10
 */
public class DoTestOfNews {
    private String name;

    public static void main(String[] args) {
        DoTestOfNews doTestOfNews = new DoTestOfNews();
        Thread[] ts = new Thread[2];
        ts[0] = new Thread(() -> {
            try {
                Thread.currentThread().sleep(2000);
                System.out.println("t1 已启动");
                if (doTestOfNews.name == null) {
                    // ********** park **********
                    //LockSupport.park(ts[0]);

                    // ********** join **********
                    //ts[1].join();// 内部调用ts[1].wait()
                    //synchronized (ts[1]) {
                    //    ts[1].wait();
                    //}

                    // ********** wait **********
                    synchronized (doTestOfNews) {
                        doTestOfNews.wait();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t1 name=" + doTestOfNews.name);
        });
        ts[1] = new Thread(() -> {
            try {
                Thread.currentThread().sleep(2000);
                System.out.println("t2 已启动");
                doTestOfNews.name = "我是t2,付个值";
                // ********** park **********
                //LockSupport.unpark(ts[0]);

                // ********** join **********
                // 无须显示做啥，ts[1]结束后会回调ts[1].notifyAll

                // ********** wait **********
                synchronized (doTestOfNews) {
                    doTestOfNews.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        ts[0].start();
        ts[1].start();
    }

}
